//这里只暴漏模块方法，使用需要在相应router上注册
var UserModel = require("./../../../models").User;
var jwt=require('jsonwebtoken');
var tokenM=require('./token_manage');
exports.register = function (req, res) {
    var UsersEntity = new UserModel(req.body);
    UserModel.findOne({name:req.body.name})
    .exec(function (err, user) {
        if (err)
            return res.json({err:err});
        if (user) {
            return res.json({err:"用户名已经存在"});
        }
        UsersEntity.save(function (err, user) {
            if (err) {
                return res.json({err:err});
            }
            res.json({
            	success:true
            });
        });
    });
};

exports.login = function (req, res) {
    UserModel.findOne({name:req.body.name}).exec(function (err, user) {
        if (err)
            return res.json({err:err});
        if (!user) {
            return res.json({err:'用户名不存在'});
        }
        if (!user.authenticate(req.body.password)) {
            return res.json({err: '密码错误'});
        }
      	var userTokenInfo={
			name:user.name,
			password:user.password
  		}
        var token = jwt.sign(userTokenInfo, tokenM.conf.secret, { expiresIn:tokenM.conf.expiration});
        user.token=token;
        user.save();
        res.json({ token: token });
    });
};

/**
 * 
 */
exports.data = function(req,res){
	return UserModel.findOne({name:req.user.name}).select('name role').exec(function(err,user){
		if (err)
            return res.json({err:err});
        if (!user) {
            return res.json({err:'用户名不存在'});
        }
        if (user.password!=req.body.password) {
            return res.json({err: '密码错误'});
        }
	});
};
exports.logout = function (req, res) {
	UserModel.findOne({name:req.user.name}).exec(function (err, user) {
        if (err)
            return res.json({err:err});
        user.token='';
        user.save();
        res.json({
        	success:true
        });
    });
};
